<script setup>
import { productDeleteProductCarouselService, productGetMerchantProductEditService, productPostMerchantProductService, productPostProductCarouselService, productPostSkuSpecService, productPutMerchantProductBasicInfoService, productPutMerchantProductSkuService } from '@/api/product'
import {
  Back,
  Edit,
  Plus
} from '@element-plus/icons-vue'
import { shallowRef, ref, reactive, computed, onMounted, onUnmounted, onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router';
import { useRouter } from 'vue-router'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 CSS

const router = useRouter();
const route = useRoute();

onMounted(() => {
  document.documentElement.classList.remove('dark');
})
onUnmounted(() => {
  document.documentElement.classList.add('dark');
})

/* 接收传参 */
const productId = route.query.id;

/* 获取页面渲染数据 */
const getEditData = async () => {
  const res = await productGetMerchantProductEditService(productId);
  const { title, coverUrl, description, price, carouselFileList, productSkuList } = res.data.data;
  // 基本信息
  curCoverUrl.value = coverUrl;
  basicForm.title = title;
  basicForm.description = description;
  basicForm.price = price;

  // 轮播图
  if (carouselFileList) {
    currentCarouselFileList.value = carouselFileList;
  }

  // 提取商品规格项与值
  if (productSkuList) {
    skuList.value = productSkuList;
    copySkuList();

    for (const productSku of productSkuList) {
      for (const spec of productSku['specs']) {
        if (!specKeyValueListMap.has(spec.key)) {
          specKeyValueListMap.set(spec.key, new Set());
        }
        specKeyValueListMap.get(spec.key).add(spec.value);

        if (!specKeyValueListIdMap.has(spec.keyId)) {
          specKeyValueListIdMap.set(spec.keyId, new Set());
        }

        specKeyValueListIdMap.get(spec.keyId).add(spec.valueId);

        // 记录 name 到 id 的映射
        specKeyValueNameToIdMap.set(spec.key, spec.keyId);
        specKeyValueNameToIdMap.set(spec.value, spec.valueId);
      }
    }
  }
}
if (productId) {
  getEditData();
}

/* 基本信息 */
const curCoverUrl = ref('');
const basicForm = reactive({
  title: '',
  description: '',
  price: 0,
  cover: null
})

const putBasicInfo = async () => {
  await productPutMerchantProductBasicInfoService(productId, basicForm);
}

const postBasicInfo = async () => {
  await productPostMerchantProductService(basicForm);
  router.push('/merchant/self');
}

// 封面
const onCoverChange = (file) => {
  basicForm.cover = file.raw;
  curCoverUrl.value = URL.createObjectURL(file.raw)
}

// 商品描述
const editDescriptionVisible = ref(false);

// 编辑器实例
const editorRef = shallowRef()
// 工具栏配置
const toolbarConfig = {
  excludeKeys: ['fullScreen'], // 排除不需要的菜单
}
// 编辑器配置
const editorConfig = {
  placeholder: '正文',
  MENU_CONF: {
    uploadImage: {
      async customUpload(file, insertFn) {
        // const res = await mediaPostService(file);
        // const { id, path } = res.data.data;
        // publishFormModel.value.mediaIdList.push(id);
        // insertFn(path, '图片描述', '');
      }
    },
    uploadVideo: {
      async customUpload(file, insertFn) {
        // const res = await mediaPostService(file);
        // const { id, path } = res.data.data;
        // publishFormModel.value.mediaIdList.push(id);
        // insertFn(path, '视频描述', '');
      }
    }
  }
}
// 编辑器创建后的回调
const handleCreated = (editor) => {
  editorRef.value = editor
}
// 组件销毁时，及时销毁编辑器
onBeforeUnmount(() => {
  if (editorRef.value) {
    editorRef.value.destroy()
  }
})

/* 商品轮播图 */
const currentCarouselFileList = ref([]); // 初始已有文件

const uploadCarousel = async (options) => {
  const { file } = options;

  await productPostProductCarouselService(productId, file);
}

const handleRemoveBanner = async (file) => {
  await productDeleteProductCarouselService(productId, file.id)
}

/* 商品规格 */
const specKeyValueListMap = reactive(new Map());
const specKeyValueListIdMap = reactive(new Map());
const specKeyValueNameToIdMap = new Map();
const skuList = ref([]);

const getSpecValue = (specs, specKey) => {
  for (const spec of specs) {
    if (spec.key === specKey) {
      return spec.value;
    }
  }
  return '';
}

// 规格管理
const specForm = reactive({
  specKey: '',
  specValue: ''
})

const addSpec = async () => {
  const addSpecKeyId = specKeyValueNameToIdMap.get(specForm.specKey);
  const addSpecValueId = specKeyValueNameToIdMap.get(specForm.specValue);

  // 判断是否新增规格
  const isNewSpecKey = !specKeyValueListIdMap.has(addSpecKeyId);
  if (isNewSpecKey) {
    // 新增规格
    if (skuList.value.length === 0) { // 原先没有任何SKU，直接添加。
      await productPostSkuSpecService({ productId: productId, type: 'new', spec: { key: specForm.specKey, value: specForm.specValue } })
    } else {
      await productPostSkuSpecService({ productId: productId, type: 'new', spec: { key: specForm.specKey, value: specForm.specValue } })
    
    }
  } else {
    // 不是新增规格（则会新增SKU）
    const specKeyValueListIdArray = Array.from(specKeyValueListIdMap.entries())
    const result = [];

    const dfs = (idx, cur) => {
      if (idx === specKeyValueListIdArray.length) {
        result.push({ specs: Array.from(cur) });
        return;
      }

      for (const specValue of specKeyValueListIdArray[idx][1]) {
        if (specKeyValueListIdArray[idx][0] === addSpecKeyId) {
          cur.push({keyId: specKeyValueListIdArray[idx][0], valueId: null});
          dfs(idx + 1, cur);
          cur.pop()
          break
        } else {
          cur.push({keyId: specKeyValueListIdArray[idx][0], valueId: specValue});
          dfs(idx + 1, cur);
          cur.pop()
        }
      }
    }
    dfs(0, []);
    await productPostSkuSpecService({ productId: productId, type: 'old', spec: { keyId: addSpecKeyId, value: specForm.specValue }, skus: [...result.map(obj => obj.specs)] })
  }

  // 清理数据
  specForm.specKey = '';
  specForm.specValue = '';
  skuList.value = [];
  specKeyValueListMap.clear();
  specKeyValueListIdMap.clear();
  specKeyValueNameToIdMap.clear();
  // 重新渲染
  getEditData();
}

const removeSpec = (index) => {
  specs.value.splice(index, 1)
}

/* SKU 管理 */
let skuListCopy = [];
const copySkuList = () => {
  for (const sku of skuList.value) {
    const skuCopy = {};
    skuCopy['skuId'] = sku['skuId'];
    skuCopy['price'] = sku['price'];
    skuCopy['stock'] = sku['stock'];
    skuListCopy.push(skuCopy); 
  }
}

const putSku = async () => {
  console.log(skuListCopy)
  // 获取更改的 sku 列表
  const changeSkuList = []
  for (const sku of skuList.value) {
    for (const skuCopy of skuListCopy) {
      if (sku['skuId'] === skuCopy['skuId']) {
        // 检查是否变更
        if (sku['price'] !== skuCopy['price'] || sku['stock'] !== skuCopy['stock']) {
          changeSkuList.push(sku);
        }
        break;
      }
    }
  }

  await productPutMerchantProductSkuService(changeSkuList);

  // 更新拷贝列表
  skuListCopy = [];
  copySkuList();
}


</script>

<template>
  <div class="page-container">
    <el-button type="text" @click="router.go(-1)" class="back-btn">
      <el-icon><Back /></el-icon>
    </el-button>

    <el-form label-position="top" class="form-container">
      <!-- 基本信息 -->
      <el-card class="form-section">
        <template #header>
          <div class="card-header">基本信息</div>
        </template>
        
        <el-form-item label="商品标题" required>
          <el-input v-model="basicForm.title" placeholder="请输入商品标题" />
        </el-form-item>

        <el-form-item label="商品基础价格" required>
          <el-input v-model="basicForm.price" placeholder="请输入商品价格" />
        </el-form-item>

        <!-- 封面图 -->
        <el-form-item label="商品封面图" required>
          <el-upload
            class="cover-upload"
            action="#"
            :show-file-list="false"
            :on-change="onCoverChange"
            :auto-upload="false"
            accept="image/*"
          >
            <img v-if="curCoverUrl" :src="curCoverUrl" class="cover-image" />
            <el-icon v-else class="cover-upload-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸：800x800像素，支持JPG/PNG格式</div>
        </el-form-item>

        <el-form-item label="商品描述">
          <el-button type="primary" :icon="Edit" @click="editDescriptionVisible = true">编辑商品描述</el-button>
        </el-form-item>

        <template #footer>
          <div style="display: flex; justify-content: flex-end; align-items: center;">
            <el-button type="danger" @click="(productId ? putBasicInfo : postBasicInfo)()"><strong>保存商品基本信息</strong></el-button>
          </div>
        </template>
      </el-card>

      <el-card class="form-section" v-if="productId">
        <template #header>
          <div class="card-header">商品轮播图</div>
          <div class="sub-header">最多可上传10张图片，建议尺寸：750x750像素</div>
        </template>

        <el-upload
          action="#"
          list-type="picture-card"
          :file-list="currentCarouselFileList"
          :on-remove="handleRemoveBanner"
          :http-request="uploadCarousel"
          accept="image/*"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <template #footer>
          <div style="display: flex; justify-content: flex-end; align-items: center;">
            <el-button type="danger"><strong>保存商品轮播图</strong></el-button>
          </div>
        </template>
      </el-card>

      <!-- 规格设置 -->
      <el-card class="form-section" v-if="productId">
        <template #header>
          <div class="card-header">商品规格</div>
        </template>

        <div v-for="[key, valueList] in specKeyValueListMap" :key="key" class="spec-item">
          <div class="spec-key">{{ key }}</div>
          <div class="spec-value-container">
            <el-tag class="spec-value" type="danger" v-for="value in valueList">{{ value }}</el-tag>
          </div>
        </div>

        <el-form class="spec-from">
          <el-form-item label="规格项"><el-input v-model="specForm.specKey"></el-input></el-form-item>
          <el-form-item label="规格值"><el-input v-model="specForm.specValue"></el-input></el-form-item>
          <el-button type="primary" @click="addSpec" :icon="Plus">
            添加规格
          </el-button>
        </el-form>
      </el-card>

      <!-- SKU管理 -->
      <el-card class="form-section" v-if="skuList && skuList.length > 0">
        <template #header>
          <div class="card-header">SKU管理</div>
        </template>

        <el-table :data="skuList" border class="sku-table">
          <el-table-column 
            v-for="specKey in specKeyValueListMap.keys()" 
            :key="specKey"
            :label="specKey"
          >
            <template #default="{ row }">
              {{ getSpecValue(row.specs, specKey) }}
            </template>
          </el-table-column>
          
          <el-table-column label="价格" width="150">
            <template #default="{ row }">
              <el-input-number 
                v-model="row.price"
                :min="0"
                controls-position="right"
              />
            </template>
          </el-table-column>

          <el-table-column label="库存" width="150">
            <template #default="{ row }">
              <el-input-number
                v-model="row.stock"
                :min="0"
                controls-position="right"
              />
            </template>
          </el-table-column>
        </el-table>

        <template #footer>
          <div style="display: flex; justify-content: flex-end; align-items: center;">
            <el-button type="danger" @click="putSku"><strong>保存商品SKU</strong></el-button>
          </div>
        </template>
      </el-card>
    </el-form>
  </div>

  <el-drawer
    size="100%"
    v-model="editDescriptionVisible"
    title="编辑商品描述"
    class="edit-drawer"
  >
    <div class="edit-description-container">
      <div class="toolbar-container">
        <!-- 编辑器工具栏 -->
        <Toolbar
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          style="border-bottom: 1px solid #ccc"
        />
      </div>
      <div class="main-container">
        <!-- 编辑器主体 -->
        <Editor
          v-model="basicForm.description"
          :defaultConfig="editorConfig"
          style="width: 50%; height: calc(100% - 40px); overflow-y: hidden;"
          @onCreated="handleCreated"
        />
        <div 
          class="preview-content"
          v-html="basicForm.description"
        ></div>
      </div>
    </div>
  </el-drawer>
</template>

<style lang="scss" scoped>
/* 新增样式 */
.cover-upload {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409eff;
    }
  }

  .cover-image {
    width: 200px;
    height: 200px;
    object-fit: cover;
    display: block;
  }

  .cover-upload-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 200px;
    text-align: center;
    line-height: 200px;
  }
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-left: 5px;
  margin-top: 8px;
}

.sub-header {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.edit-description-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.toolbar-container {
  border-right: 1px solid #e4e7ed;
}

.main-container {
  display: flex;
  width: 100%;
  flex: 1;
}

.preview-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex-wrap: wrap;
  width: 50%;
  border-left: 1px solid rgb(163, 163, 163);
  padding: 0px 20px;
  line-height: 1.5;

  :deep(p) {
    word-break: break-all;
  }
}

/* 重置编辑器默认样式 */
.preview-content :deep(img) {
  max-width: 100%;
}

.preview-content :deep(table) {
  border-collapse: collapse;
}

.preview-content :deep(td),
.preview-content :deep(th) {
  border: 1px solid #ddd;
  padding: 8px;
}

/* 调整轮播图上传样式 */
:deep(.el-upload-list--picture-card) {
  .el-upload-list__item {
    width: 120px;
    height: 120px;
  }
}

:deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
  line-height: 120px;
}

.page-container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;

  .back-btn {
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    font-size: 25px;
    color: black;

    .el-icon {
      margin-right: 8px;
    }
  }

  .form-section {
    margin-bottom: 24px;

    .card-header {
      font-size: 16px;
      font-weight: 500;
    }
  }

  .spec-item {
    margin-bottom: 24px;
    padding: 16px;
    border-radius: 4px;
    background: #f8f9fa;

    .spec-key {
      font-size: 20px;
      font-weight: bolder;
      margin-bottom: 15px;
    }

    .spec-value-container {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      margin-bottom: 12px;

      .spec-value {
        margin-right: 4px;
      }
    }
  }

  .spec-from {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .el-form-item {
      margin-bottom: 0px;
    }
  }

  .sku-table {
    margin-top: 16px;

    ::v-deep .el-input-number {
      width: 100px;
    }
  }
}

.edit-drawer {
  :deep(.el-drawer__header) { 
    color: black;
    font-weight: bolder;
    
    .el-drawer__title {
      font-size: 25px;
    }
  }
}
</style>